package com.promise.jokerdream.work.faction

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 帮派黄金联赛
class FactionLeagueWork(uin: String): BaseWork(uin) {

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override val name: String
        get() = "帮派黄金联赛"

    override suspend fun executeWork(): WorkResult {
        return try {
            // 查询帮派黄金联赛信息
            val queryResult = gameApi.queryFactionLeague()

            queryResult.foldWithApiException(
                onSuccess = { response ->
                    var currentResponse = response
                    
                    // 如果待领奖状态，先执行领奖
                    if (currentResponse.status == 1 || currentResponse.status == 2) {
                        // status=1时使用op=5，status=2时使用op=7
                        val op = if (currentResponse.status == 1) "5" else "7"
                        val claimResult = gameApi.factionLeagueClaimReward(op)
                        claimResult.foldWithApiException(
                            onSuccess = { claimResponse ->
                                historyManager.addHistory(name, claimResponse.getDescription())
                                // 领奖成功，使用返回的更新后的响应
                                currentResponse = claimResponse
                            },
                            onFailure = { code, msg ->
                                historyManager.addHistory(name, msg, code)
                            }
                        )
                    }
                    
                    // 如果未报名状态，执行报名（参与防守）
                    if (currentResponse.status == 3 && currentResponse.signUp == 0) {
                        executeSignUp()
                    } else {
                        WorkResult.Success
                    }
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 执行报名（参与防守）
     */
    private suspend fun executeSignUp(): WorkResult {
        return try {
            val signUpResult = gameApi.factionLeagueDefend()
            signUpResult.foldWithApiException(
                onSuccess = { response ->
                    historyManager.addHistory(name, response.getDescription())
                    WorkResult.Success
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
}